package com.situ.web.filter;


import com.situ.web.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

// /*拦截所有
//@WebFilter(filterName = "login", urlPatterns = "/*")
public class LoginFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String uri = request.getRequestURI();
        System.out.println("uri: " + uri);

        // /user?method=login
        // /user?method=selectAll
        // /user
        String method = request.getParameter("method");

        //对于那些要去完成登录的请求，应该放行
        if (uri.startsWith("/static")
                || uri.equals("/login.jsp")
                || uri.equals("/fail.jsp")
                || (uri.equals("/user") && "login".equals(method))) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            response.sendRedirect("/login.jsp");
            return;
        }

        //user这个令牌不是null，用户已经登录
        //如果加了这了这句话代表放行，继续往后执行
        //1.如果后面还有filter就访问后面的filter 2.没有filter就访问后台资源
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
